package coroutines

/**
 * 测试在一个线程中，多个协程会不会并行运行
 * 答案：不会，一个线程中的多个协程肯定是串行的
 */
import kotlinx.coroutines.*



private fun doSomething(str:String){
    GlobalScope.async(Dispatchers.Main+CoroutineName(str)){
        repeat(1000){
            println("doSomething in thread ${Thread.currentThread().name} coroutine:${coroutineContext[CoroutineName.Key]} ,it:$it")
        }
        println("doSomething in thread ${Thread.currentThread().name} coroutine:${coroutineContext[CoroutineName.Key]} end")
    }
}
fun main() {
  val singleThreadContext=  newSingleThreadContext("测试并发线程")
   val one:Job= GlobalScope.async(singleThreadContext+CoroutineName("协程1"),CoroutineStart.LAZY){
        repeat(1000){
            println("doSomething in thread ${Thread.currentThread().name} coroutine:${coroutineContext[CoroutineName.Key]} ,it:$it--->${getNow()}")
        }
        println("doSomething in thread ${Thread.currentThread().name} coroutine:${coroutineContext[CoroutineName.Key]} end")
    }
   val two:Job= GlobalScope.async(singleThreadContext+CoroutineName("协程2"),CoroutineStart.LAZY){
        repeat(1000){
            println("doSomething in thread ${Thread.currentThread().name} coroutine:${coroutineContext[CoroutineName.Key]} ,it:$it--->${getNow()}")
        }
        println("doSomething in thread ${Thread.currentThread().name} coroutine:${coroutineContext[CoroutineName.Key]} end")
    }

    println("启动两个协程")
    one.start()
   two.start()
    Thread.sleep(1000 * 5)
    println("main end in thread ${Thread.currentThread().name}")
}